#include <WinSock2.h>
#include <WS2tcpip.h>
#include "Net.h"
#pragma comment(lib,"ws2_32.lib")

#define V_SOCK_LO 2
#define V_SOCK_HI 2
#define V_SOCK_REQUEST MAKEWORD(V_SOCK_LO, V_SOCK_HI)

AUTO_INSTANCE_CPP(Net)
Net::Net()
{}

void Net::ip_itot(SOCKADDR_IN* sockaddrin, TCHAR* ip)
{
	_stprintf_s(ip, LEN_IP+1, "%d.%d.%d.%d",
		sockaddrin->sin_addr.S_un.S_un_b.s_b1,
		sockaddrin->sin_addr.S_un.S_un_b.s_b2,
		sockaddrin->sin_addr.S_un.S_un_b.s_b3,
		sockaddrin->sin_addr.S_un.S_un_b.s_b4
	);
}

void Net::ip_ttoi(SOCKADDR_IN* sockaddrin, TCHAR* ip)
{
	TCHAR *token = nullptr, *nexttoken = nullptr;
	token = _tcstok_s(ip, TEXT("."), &nexttoken);
	sockaddrin->sin_addr.S_un.S_un_b.s_b1 = _ttoi(token);
	token = _tcstok_s(nexttoken, TEXT("."), &nexttoken);
	sockaddrin->sin_addr.S_un.S_un_b.s_b2 = _ttoi(token);
	token = _tcstok_s(nexttoken, TEXT("."), &nexttoken);
	sockaddrin->sin_addr.S_un.S_un_b.s_b3 = _ttoi(token);
	token = _tcstok_s(nexttoken, TEXT("."), &nexttoken);
	sockaddrin->sin_addr.S_un.S_un_b.s_b4 = _ttoi(token);
}

int Net::Init()
{
	WSADATA wsadata;
	if (!WSAStartup(V_SOCK_REQUEST, &wsadata))
	{
		if (LOBYTE(wsadata.wVersion) != V_SOCK_LO ||
			HIBYTE(wsadata.wVersion) != V_SOCK_HI)
		{
			WSACleanup();
			return 1;
		}
	}
	return 0;
}
